package br.com.andreikeda.utility.gestor.finance.storage.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import br.com.andreikeda.utility.gestor.R;
import br.com.andreikeda.utility.gestor.finance.utils.LogUtils;

/**
 * Created by LimaoGames on 22/01/2015.
 * contact me: andreikeda87@gmail.com
 */
public class DatabaseHelper extends SQLiteOpenHelper {

    private static DatabaseHelper instance;

    private static final String NAME = "database.sqlite";
    private static final int VERSION = 1;

    private Context context;

    /**
     * Method to return a single instance (static) from this class.
     *
     * @param context - Application context.
     * @return {@link DatabaseHelper}
     */
    public static DatabaseHelper getInstance(Context context) {
        if (instance == null)
            instance = new DatabaseHelper(context, NAME, null, VERSION);
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase mLite) {
        queryCreate(mLite);
    }

    @Override
    public void onUpgrade(SQLiteDatabase mLite, int oldVersion, int newVersion) {

    }

    private DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);

        this.context = context;
    }

    /**
     * Method to query database creation.
     *
     * @param mLite - {link SQLiteDatabase} instance.
     */
    private void queryCreate(SQLiteDatabase mLite) {
        InputStream stream = context.getResources().openRawResource(R.raw.create);

        if (stream != null) {
            InputStreamReader inputreader = new InputStreamReader(stream);
            BufferedReader buffreader = new BufferedReader(inputreader);
            String line, sql = "";
            try {
                while ((line = buffreader.readLine()) != null)
                    sql += line;
            } catch (Exception e) {
                e.printStackTrace();
            }

            LogUtils.debug(getClass(), sql);
            mLite.execSQL(sql);
        }
    }
}
